local biz_name = "tkm"

ConfigRedisConnectors[biz_name]={
    host = "127.0.0.1", --192.168.2.28
    port = 6379, --6380
    unixpath = "/etc/redis/unixpath/redis.sock",
    db = NIL,
    user = NIL,
    passwd = NIL,
    queue = "k2"
}

local function tkm()
      return coroutine.create(function ()
        while true do
        ----print(".")
        --local valid = true
            local DEF_LOCATION = "0"
            --xoa redis cmd buf trong lua_State->l_G
            luredis.clear_cmd_buffer()

            --parse header
            local headerTable = request.getHeaders_key_value()
            --parse cookie
            local cookieTable = parseCookies(getStringValue(headerTable, config.COOKIE_HEADER))
            --parse parameter
            local paraTable = request.getParameters_key_value()

                --append server time to lua_State->l_G->redis_cmd_buf_append
                local createTime = os.time()
                luredis.append_cmd_buffer(createTime, config.SEPARATE_CHAR)

                --append client ip to lua_State->l_G->redis_cmd_buf_append
                local ip = request.getIP()
                luredis.append_cmd_buffer(ip, config.SEPARATE_CHAR)


                --Lay cac thong so
                --guid
                local guid = cookieTable[config.GUID_COOKIE]
                --region buffer
                local region = getStringValue(cookieTable, config.REGION_COOKIE)
                --os version buffer
                local osVersionBuf = getStringValue(cookieTable, config.OS_MOBILE_COOKIE)
                --user agent
                local userAgent = getStringValue(headerTable, config.USER_AGENT_HEADER)

                -- Khoi tao cac bien
                local cookieCreate

            local cookieDomain = ""
            if--if#6
                config.http.mobilecookie.domain and (config.http.mobilecookie.domain ~= "")
            then
                cookieDomain = config.http.mobilecookie.domain
            else
                cookieDomain = config.http.setcookie.domain
            end--end of if#6

            --kiem tra xem co region chua: cookie: __C
            --neu chua co vao hget lay, neu ko co, set default = 0. Set lai vao cookie
            local region_number = tonumber(region)
            if
                (not region_number) or (region_number <=3)
            then
                --get region from redis location
                local reply_type
                reply_type, region = util.redis_command(config.HGET_MOBILE_REDIS, luredis.send_cmd, "hget "..ConfigRedisConnectors[config.HGET_MOBILE_REDIS].queue.." "..c_inet_network(ip))
                if--if#7
                            (region == nil) or (region == "") or (reply_type == 6) --if error, reply_type = REDIS_REPLY_ERROR = 6
                then
                    region = DEF_LOCATION
                else
                    region_number = tonumber(region)
                    if--if#7.1
                        region_number and(region_number > 3)
                    then--
                        --Them region cookie
                        pushCookieHeader(config.REGION_COOKIE, region, os.time()+86400, "/", cookieDomain, false)
                    else
                        region = DEF_LOCATION
                    end--end of if#7.1
                end--end of if#7
            end

            --append cookie create
            --cookie create: thoi gian tao guid cookie
            if --if#2
                guid
            then
                --get cookie create
                cookieCreate = getStringValue(cookieTable,config.CREATE_COOKIE)
                --append cookie create
                luredis.append_cmd_buffer(cookieCreate, config.SEPARATE_CHAR)
            else
                guid = create_guid(createTime, ip)
                if not guid then break end
                --apend cookie create
                luredis.append_cmd_buffer(createTime, config.SEPARATE_CHAR)
                --set cookie
                --them cookie header vao _reply
                if--if#4
                        userAgent and userAgent ~= ""
                then
                        if--if#5
                                not(string.find(userAgent, "Safari")and (not string.find(userAgent, "Chrome")))
                        then
                                --Them guid cookie
                                --Them create cookie
                                pushCookieHeader(config.GUID_COOKIE, guid, config.EXPIRE_TIME+createTime, "/", cookieDomain, false)
                                pushCookieHeader(config.CREATE_COOKIE, createTime, config.EXPIRE_TIME+createTime, "/", cookieDomain, false)
                        end--end of if#5
                end--end of if#4
            end--end of if#2

            local osVersion
            if
                string.len(osVersionBuf) < 3
            then
                osVersion = parseUserAgent(userAgent)
                pushCookieHeader(config.OS_MOBILE_COOKIE, osVersion, config.EXPIRE_TIME+createTime, "/", cookieDomain, false)
            end

            --append __uid, __C
            luredis.append_cmd_buffer(guid, config.SEPARATE_CHAR, guid, config.SEPARATE_CHAR, region, config.SEPARATE_CHAR)

            --append OS to redis_cmd_value_buf
            if osVersion then
                luredis.append_cmd_buffer(osVersion, config.SEPARATE_CHAR)
            else
                if osVersionBuf then
                    luredis.append_cmd_buffer(osVersionBuf, config.SEPARATE_CHAR)
                else
                luredis.append_cmd_buffer("", config.SEPARATE_CHAR)
                end
            end


            --append to redis_cmd_buf_value: flash enable, java enable, resolution, color, user agent
            local flashParam = getStringValue(paraTable, config.TRACKING_MOBILE_FE_PARAM)
            local javaParam = getStringValue(paraTable, config.TRACKING_MOBILE_JE_PARAM)
            local screenResolutionParam = getStringValue(paraTable, config.TRACKING_MOBILE_SR_PARAM)
            local colorParam = getStringValue(paraTable, config.TRACKING_MOBILE_SC_PARAM)

            luredis.append_cmd_buffer(getStringValue(paraTable, config.TRACKING_MOBILE_FE_PARAM), config.SEPARATE_CHAR, getStringValue(paraTable, config.TRACKING_MOBILE_JE_PARAM), config.SEPARATE_CHAR, getStringValue(paraTable, config.TRACKING_MOBILE_SR_PARAM), config.SEPARATE_CHAR, getStringValue(paraTable, config.TRACKING_MOBILE_SC_PARAM), config.SEPARATE_CHAR,userAgent)


            --push data to redis--
            luredis.send_cmd_buffer(getRedisConnector(biz_name),"lpush "..ConfigRedisConnectors[biz_name].queue.. " %s");


            --add header to reply--
            --Them content type header
            reply.pushHeader(config.CONTENT_TYPE_HEADER, "application/javascript")

            --Them server header
            reply.pushHeader(config.SERVER_HEADER, config.http.servername)

            --Append to reply content
            --su dung luaState_temp_buf de chua gia tri tam thoi cua content
            luaState_temp_buf_clear()
            luaState_temp_buf_append("function getCookie(a){if(document.cookie.length>0&&(c_start=document.cookie.indexOf(a+\"=\"),c_start!=-1)){c_start=c_start+a.length+1;c_end=document.cookie.indexOf(\";\",c_start);if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end))}return\"\"}function setCookie(a,d,c){var b=new Date;b.setDate(b.getDate()+c);document.cookie=a+\"=\"+escape(d)+(c==null?\"\":\";path=\\/;expires=\"+b.toUTCString())}var _ADSLocation=getCookie(\"__R\"),_ADSCity=getCookie(\"__RC\");")

            --check city id & region id--
            local cityID = tonumber(region)
            if
                cityID and ((cityID == 6) or (cityID < 0) or (cityID > 68))
            then
                luaState_temp_buf_append("parseInt(_ADSCity)!=", cityID, " &&setCookie('__RC',", cityID, "%d ,7);", "parseInt(_ADSLocation)!= 0", "&&setCookie('__R', 0", ",7);")
            else
                luaState_temp_buf_append("parseInt(_ADSCity)!=", cityID, " &&setCookie('__RC',", cityID, " ,7);", "parseInt(_ADSLocation)!= 0", region_mobile_table[cityID], "&&setCookie('__R', 0", ",7);", region_mobile_table[cityID], ",7);" )
            end
            --Append to reply content: set cookies for __M --
            luaState_temp_buf_append("setCookie('__M','")
            if  osVersion then
                luaState_temp_buf_append(osVersion)
            else
                if  osVersionBuf then
                    luaState_temp_buf_append(osVersionBuf)
                else
                    luaState_temp_buf_append("")
                end
            end
            luaState_temp_buf_append("',7);")

            local content = luaState_temp_buf_get()
            reply.setContent(content)
            luaState_temp_buf_clear()

            reply.setStatus(reply.status_type.ok);
            reply.pushHeader("Content-Length", string.len(content))


--print("\n\nend of function----")

                coroutine.yield()
            end--end of while 1
            f[biz_name] = tkm()
----------------
        end)
    end
f[biz_name] = tkm()
